<template>
	<el-form ref="loginForm" :model="form" :rules="rules" label-width="0" size="large" @keyup.enter="login">
		<el-form-item prop="user">
			<el-input v-model="form.user" prefix-icon="el-icon-user" clearable :placeholder="$t('login.userPlaceholder')">
				<template #append>
					<el-select v-model="userType" style="width: 130px;">
						<el-option :label="$t('login.admin')" value="admin"></el-option>
						<el-option :label="$t('login.user')" value="user"></el-option>
					</el-select>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item prop="password">
			<el-input v-model="form.password" prefix-icon="el-icon-lock" clearable show-password :placeholder="$t('login.PWPlaceholder')"></el-input>
		</el-form-item>
		<el-form-item style="margin-bottom: 10px;">
				<el-col :span="12">
					<el-checkbox :label="$t('login.rememberMe')" v-model="form.autologin"></el-checkbox>
				</el-col>
				<el-col :span="12" class="login-forgot">
					<router-link to="/reset_password">{{ $t('login.forgetPassword') }}？</router-link>
				</el-col>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" style="width: 100%;" :loading="islogin" round @click="login">{{ $t('login.signIn') }}</el-button>
		</el-form-item>
		<div class="login-reg">
			{{$t('login.noAccount')}} <router-link to="/user_register">{{$t('login.createAccount')}}</router-link>
		</div>
	</el-form>
</template>

<script>
	import BaseUI from '@/views/components/baseUI'
	import { getToken } from '@/api/auth'
	import {
  	setLocalToken,
  	setLocalCurrentUser,
  	setLocalRouters,
  	setLocalDataPermisions,
  	setLocalCurrentCompany } from '@/utils/auth'
	export default {
		extends: BaseUI,
		data() {
			return {
				userType: 'admin',
				form: {
					user: "system",
					password: "123456",
					autologin: false
				},
				rules: {
					user: [
						{required: true, message: this.$t('login.userError'), trigger: 'blur'}
					],
					password: [
						{required: true, message: this.$t('login.PWError'), trigger: 'blur'}
					]
				},
				islogin: false,
			}
		},
		watch:{
			userType(val){
				if(val == 'admin'){
					this.form.user = 'admin'
					this.form.password = 'admin'
				}else if(val == 'user'){
					this.form.user = 'user'
					this.form.password = 'user'
				}
			}
		},
		mounted() {

		},
		methods: {
			doLogin() {
				this.$refs.loginForm.validate(valid => {
					if (valid) {
						// if (this.loginForm.captcha.toLowerCase() === this.tmpCaptcha.toLowerCase()) {
							// this.$store.dispatch('setLoading', true)
							this.islogin = true
							getToken(this.form.user, this.form.password)
							.then(responseData => {
								if(responseData.code == 100) {
									console.log(responseData.data);
									this.handleLoginInfo(responseData.data)
								} else {
									this.isError = true
									this.loginError = responseData.msg
									// this.createCaptcha()
									// this.$store.dispatch('setLoading', false)
								}
								this.islogin = false
							})
							.catch(error => {
								// this.createCaptcha()
								// this.$store.dispatch('setLoading', false)
								this.outputError(error)
								this.islogin = false
							})
					} else {
						this.isError = true
						this.loginError = '验证码输入错误'
						// this.createCaptcha()
						// this.$store.dispatch('setLoading', false)
					}
				})
			},
			handleLoginInfo(userData) {
				// TODO
				window.currentUser = {
					id: userData.userId,
					name: userData.username,
					company: {
							id: 0
					}
				}
				setLocalCurrentUser({
					id: userData.userId,
					name: userData.username,
					loginname: userData.loginname,
					company: userData.company,
					department: userData.department,
					isActive: userData.isActive,
					changePwdDate: userData.changePwdDate
				})
				setLocalCurrentCompany({
					id: userData.company.id,
					code: userData.company.code,
					name: userData.company.name
				})
				setLocalToken(userData.token)
				setLocalRouters(userData.routers)
				setLocalDataPermisions(userData.dataPermisions)

				userData.routers.forEach((item) => {
					// item.path = item.path
					// item.name = item.name
					item.meta = {
						icon: "el-icon-info-filled",
						title: item.name,
						type: "menu",
						routerId: item.id
					}

					// 合并 properties 属性到meta
					const properties = item.properties ? JSON.parse(item.properties) : {}
					item.meta = {...item.meta, ...properties}
				})
				const menu = this.treeMenu(userData.routers)
				this.$TOOL.data.set("MENU", menu)

				this.$router.replace({
					path: '/'
				})
				this.$message.success("Login Success 登录成功")
				this.islogin = false
			},
			async login(){
				var validate = await this.$refs.loginForm.validate().catch(()=>{})
				if(!validate){ return false }

				var data = {
					username: this.form.user,
					password: this.$TOOL.crypto.MD5(this.form.password)
				}
				this.doLogin()
			},
			treeMenu(data) {
				data.forEach(function(item) {
					delete item.children;
				});

				let map = new Map();
				data.forEach(function(item) {
					map.set(item.id, item)
				});

				let temp = [];
				data.forEach(function(item) {
					let parent = map.get(item.parent.id);

					if (parent) {
						(parent.children || (parent.children = [])).push(item);
					} else {
						temp.push(item);
					}
				});
				return temp;
			}
		}
	}
</script>

<style>
</style>
